package org.tools.gson;

import java.lang.reflect.Field;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;

/** 
 * 顶级类系列化策略
 *
 * <pre> 
 * 构建组：e-tools
 * 作者：eddy
 * 邮箱：1546077710@qq.com
 * 日期：2017年4月23日-下午5:53:17
 * 版权：E源时代
 * </pre>
 */
public class SuperclassExclusionStrategy implements ExclusionStrategy {

	//@Override
	public boolean shouldSkipField(FieldAttributes f) {
		String fieldName = f.getName();
		Class<?> theClass = f.getDeclaringClass();
		return isFieldInSuperclass(theClass, fieldName);
	}

	//@Override
	public boolean shouldSkipClass(Class<?> clazz) {
		return false;
	}

	private boolean isFieldInSuperclass(Class<?> subclass, String fieldName) {
		Class<?> superclass = subclass.getSuperclass();
		Field field = null;

		while (superclass != null) {
			field = getField(superclass, fieldName);
			if (field != null)
				return true;
			superclass = superclass.getSuperclass();
		}
		return false;
	}

	private Field getField(Class<?> clazz, String fieldName) {
		try {
			return clazz.getDeclaredField(fieldName);
		} catch (Exception e) {
			return null;
		}
	}
}